﻿using System;
using CzfRow = System.Collections.Generic.Dictionary<string, string>;
using LitJson;
using System.Collections;

namespace CzfSDK
{
	public class CzfModel
	{
		public CzfRow row;

		public virtual void Import(CzfRow data)
		{
			try{
				row = data;
				ImportDict(data);
			}catch(Exception e){
				CzfLog.Error ("[" + this.GetType ().Name + "]Import Error:" + Tool.ToJson(data), null);
				throw e;
			}
		}

		public virtual void Import(JsonData json)
		{
			try{
				ImportDict(json);
			}catch(Exception e){
				CzfLog.Error ("[" + this.GetType ().Name + "]Import Error:" + json.ToJson(), null);
				throw e;
			}
		}

		/// <summary>
		/// 使用了反射,如果需要提高效率,可以用普通方式重写
		/// </summary>
		/// <param name="data">Data.</param>
		protected virtual void ImportDict(IDictionary data)
		{
			var type = this.GetType ();
			foreach (var key in data.Keys) {
				var field = type.GetField (key.ToString());
				if (field != null) {
					var notMeta = field.GetCustomAttributes (typeof(CzfFieldAttribute), false);
					if (notMeta.Length > 0)
						field.SetValue (this, Convert.ChangeType (data [key].ToString(), field.FieldType));
				}
			}
		}

		/// <summary>
		/// 使用了反射,如果需要提高效率,可以用普通方式重写
		/// </summary>
		/// <returns>The czf row.</returns>
		public virtual CzfRow ExportCzfRow()
		{
			var ret = new CzfRow ();
			var type = this.GetType ();
			foreach (var field in type.GetFields()) {
				var notMeta = field.GetCustomAttributes (typeof(CzfFieldAttribute), false);
				if (notMeta.Length > 0) {
					ret [field.Name] = field.GetValue (this).ToString ();
				}
			}
			row = ret;
			return ret;
		}
	}
}
